package com.avengers.core.kit;

import com.avengers.common.lock.AvengersReentrantLock;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;

/**
 * @author yu.wang
 * @since 2019-12-13 18:42
 **/
public class LockKit {

    private static final Map<Integer, Lock> auctionLockMap = new ConcurrentHashMap<>();

    public static Lock getAuctionLock(Integer auctionId) {
        if (null == auctionLockMap.get(auctionId)) {
            synchronized (("auction_" + auctionId.toString()).intern()) {
                if (null == auctionLockMap.get(auctionId)) {
                    auctionLockMap.put(auctionId, new AvengersReentrantLock(auctionId.toString()));
                }
            }
        }
        return auctionLockMap.get(auctionId);
    }

    private static final Map<String, AvengersReentrantLock> userLockMap = new HashMap<>();

    public static AvengersReentrantLock getUserLock(String userId) {
        if (null == userLockMap.get(userId)) {
            synchronized (("user_" + userId).intern()) {
                if (null == userLockMap.get(userId)) {
                    userLockMap.put(userId, new AvengersReentrantLock(userId));
                }
            }
        }
        return userLockMap.get(userId);
    }
}
